<?php

namespace App\Http\Controllers\Admin\User;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\User\Role\AllotRequest;
use App\Http\Requests\Admin\User\Role\CreateRequest;
use App\Http\Requests\Admin\User\Role\UpdateRequest;
use App\Models\Role;
use App\Repositories\Admin\User\RoleRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoleController extends BaseController
{
    //
    public function __construct()
    {
        $this->repo = new RoleRepository();
    }
    /**
     * 获取列表
     * @param Request $request
     * @return JsonResponse
     */
    public function fetchList(Request $request)
    {
        $data = $this->repo->pagination();
        return $this->success($data);
    }
    /**
     * 查单个信息
     * @param Role $role
     * @return JsonResponse
     */
    public function fetchInfo(Role $role)
    {
        $role->load(['permissions','users']);
        return $this->success($role);
    }

    /**
     * @param CreateRequest $request
     * @return JsonResponse
     */
    public function create(CreateRequest $request){
        $data = $request->only('name','display_name','description','permissions');
        $role = $this->repo->create($data);
        return $role?$this->success($role,'添加成功'):$this->error('添加失败');
    }

    /**
     * @param UpdateRequest $request
     * @param Role $role
     * @return JsonResponse
     */
    public function update(UpdateRequest $request,Role $role){
        $data = $request->only('name','display_name','description');
        $role = $this->repo->update($role,$data);
        $role->load(['permissions']);
        return !$role ? $this->error('更新失败') : $this->success($role, '更新成功');
    }

    /**
     * @param Role $role
     * @return JsonResponse
     * @throws \Exception
     */
    public function delete(Role $role){
        return $role->delete() ? $this->success([], '删除成功') : $this->error('更新失败');
    }
    /**
     * 授权
     * @param AllotRequest $request
     * @param Role $role
     * @return JsonResponse
     */
    public function allotPermission(AllotRequest $request, Role $role){
        $permissions = $request->get('permissions',[]);
        $role = $this->repo->allotPermission($permissions,$role);
        $role->load(['permissions'=>function($query){
            $query->select(['id','name','display_name']);
        }]);
        return $this->success($role);
    }
}
